package com.example.templateapp.ui.speaker

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import com.baidu.tts.client.SpeechSynthesizer
import com.baidu.tts.client.TtsMode
import com.example.templateapp.R
import com.example.templateapp.databinding.ActivitySpeakerBinding
import com.example.templateapp.ui.base.BaseAppCompatActivity
import com.example.templateapp.util.http.SpeechSynthesizerFactory
import kotlin.concurrent.thread

class SpeakerActivity : BaseAppCompatActivity() {

    private val binding: ActivitySpeakerBinding by binding(R.layout.activity_speaker)
    private val speaker by lazy { SpeechSynthesizerFactory.getInstance(this) }
    private var isLoop = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {}

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                speaker.setParam(SpeechSynthesizer.PARAM_SPEAKER, position.toString())
                speaker.initTts(TtsMode.ONLINE)
            }
        }



        binding.switch1.setOnCheckedChangeListener { buttonView, isChecked ->
            isLoop = isChecked
            speaker.pause()
        }



        binding.speakBtn.setOnClickListener {
            if (binding.speakBtn.text.toString() == "speaking...") {
                binding.speakBtn.setText("speak")
                speaker.pause()
            } else {
                val repeat = binding.switch1.isChecked
                val content = binding.content.text.toString()
                if (repeat) {
                    binding.speakBtn.setText("speaking")
                    thread {
                        while (isLoop) {
                            speaker.speak(content)
                        }
                    }
                } else {
                    speaker.speak(content)
                }
            }
        }


    }
}